﻿using CPPEI.ETL.DataServiceInterface;
using CPPEI.WebApi;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ENT = CPPEI.ETL.Domain.Entities;
using MOD = CPPEI.ETL.Domain.Models;
using SER = CPPEI.ETL.Domain.Services;

namespace CPPEI.ETL.WebApi
{
    /// <summary>
    /// 创建excel类型的数据源
    /// </summary>
    [CPPEI.WebApi.AuthPostAction("Excel", "UploadTemplate", "1.0")]
    public class UploadExcelTemplateAction : BaseAction<UploadExcelTemplateParams, UploadExcelTemplateResult>
    {
        protected override ActionResult<UploadExcelTemplateResult> OnExecute(ActionContext context, 
            SysParameters sysParameters,
            UploadExcelTemplateParams opParams)
        {
            if (opParams.Template == null || string.IsNullOrEmpty(opParams.Template.FileName))
            {
                return new ActionResult<UploadExcelTemplateResult>(false, ErrorCode.NoFile, ErrorCode.String(ErrorCode.NoFile), null);
            }

            if (!opParams.Template.FileName.ToUpper().EndsWith(".XLS")
                && !opParams.Template.FileName.ToUpper().EndsWith(".XLSX"))
            {
                return new ActionResult<UploadExcelTemplateResult>(false, ErrorCode.InvalidFileType_EXCEL, ErrorCode.String(ErrorCode.InvalidFileType_EXCEL), null);
            }

            SER.DtSerService dtSerService = new SER.DtSerService();
            string filePath = string.Format("{0}{1}.{2}", CPPEI.ETL.Domain.Configs.UploadFileDirectory, Guid.NewGuid(), GetExtension(opParams.Template.FileName));
            FileInfo fileInfo = new FileInfo(filePath);
            if(!fileInfo.Directory.Exists)
            {
                fileInfo.Directory.Create();
            }
            opParams.Template.SaveAs(filePath);

            System.Data.DataTable dataTable = CPPEI.ETL.Infrastructure.Excel.OpenXmlTool.ReadExcelHeader(filePath, opParams.FirstRowIsHeader);

            fileInfo.Delete();

            UploadExcelTemplateResult result = new UploadExcelTemplateResult();
            for (int index = 0; index < dataTable.Columns.Count; index++)
            {
                UploadExcelTemplateResult.Item item = new UploadExcelTemplateResult.Item();
                item.Name = dataTable.Columns[index].ColumnName;
                item.Type = typeof(string).FullName;
                result.Items.Add(item);
            }
            return new ActionResult<UploadExcelTemplateResult>(result);
            //if(result.IsSuccess)
            //{
            //    return new ActionResult<UploadExcelTemplateResult>(new UploadExcelTemplateResult());
            //}
            //else
            //{
            //    return new ActionResult<UploadExcelTemplateResult>(result.IsSuccess, result.ErrorCode, result.Message, null);
            //}
        }

        private string GetExtension(string fileName)
        {
            string[] segments = fileName.Split(new char[] { '.' });
            if(segments.Length > 0)
            {
                return segments.Last();
            }
            return fileName;
        }
    }

    public class UploadExcelTemplateParams
    {
        [Parameter]
        public System.Web.HttpPostedFile Template { get; set; }

        [Parameter]
        public bool FirstRowIsHeader { get; set; }
    }

    public class UploadExcelTemplateResult
    {
        public List<Item> Items = new List<Item>();

        public class Item
        {
            public string Name { get; set; }

            public string Type { get; set; }
        }
    }
}
